package com.jason.fingerprint.logic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.kymjs.aframe.http.HttpCallBack;
import org.kymjs.aframe.http.KJFileParams;
import org.kymjs.aframe.http.KJHttp;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.BaseBean;
import com.jason.fingerprint.beans.SignInRecordBean;
import com.jason.fingerprint.beans.SigninRecordResp;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.DataConfig;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.utils.CodecUtils;

/**
 * @ClassName: SignInUploadLogic
 * @Description: 上传集中教育、集中劳动、个别教育、个别劳动签到记录
 * @Author: John zhuqiangping@gmail.com
 * @Date: 2014年11月24日
 */
public class SignInUploadLogic extends Logic {

	private static final String TAG = "SignInUploadLogic";

	private Handler mHandler;
	private SignInRecordBean mSignInRecordBean = new SignInRecordBean();
	private Message mMessage;
	private String mType = "1";
	private List<SignInRecordBean> mSignInRecordBeans = new ArrayList<SignInRecordBean>();
	private int mCurrentIndex = 0;
	private int mSize = -1;
	
	public SignInUploadLogic() {

	}

	public SignInUploadLogic(AppContext appContext, Handler handler,
			String type) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mType = type;
	}

	@Override
	public void execute() {
		mCurrentIndex = 0;
		mSize = -1;
		try {
			mSignInRecordBeans = mKjdb.findAllByWhere(SignInRecordBean.class,
					"type = '" + mType + "' and state = 1");
			if (mSignInRecordBeans != null && !mSignInRecordBeans.isEmpty()) {
				mSize = mSignInRecordBeans.size();
				uploadSignInfo();
			}else {
				mMessage.what = UIHelper.SIGNIN_UPLOAD_SUCCESS;
				send();
			}
		} catch (Exception e) {
			mMessage.what = UIHelper.SIGNIN_UPLOAD_SUCCESS;
			send();
		}
	}

	@Override
	public void send() {
		mHandler.sendMessage(mMessage);
		mMessage = new Message();
	}

	private void uploadSignInfo() {
		if (mCurrentIndex >= mSize) {
			mMessage.what = UIHelper.SIGNIN_UPLOAD_SUCCESS;
			send();
			return;
		}
		mSignInRecordBean = mSignInRecordBeans.get(mCurrentIndex);
		Log.i(TAG, "--001--->mSignInRecordBean:" + mSignInRecordBean.toString());
		if (mSignInRecordBean == null) {
			mCurrentIndex ++;
			uploadSignInfo();
			return;
		}
		mParams = new KJFileParams();
		mParams.put(AppGlobal.HTTP_PARAM_IMEI, mImei);
		String sponsorId = mSignInRecordBean.getSponsorId();
		mParams.put("sponsorId", sponsorId);
		mParams.put("rymcId", mSignInRecordBean.getElectronicsId());
		mParams.put("time", mSignInRecordBean.getTime());
		mParams.put("sponsorType", mSignInRecordBean.getSponsorType());
		mParams.put("type", mSignInRecordBean.getType());
		mParams.put("flag", mSignInRecordBean.getFlag());
		String url = HttpConfig.POST_URL_EDUCOM_ADDCOMEDULIST;
		Log.i(TAG, "----->API:" + url);
		Log.i(TAG, "----->mParams:" + mParams.getParamString());
		KJHttp kjHttp = new KJHttp();
		kjHttp.post(url, mParams, new HttpCallBack() {

			@Override
			public void onSuccess(Object arg0) {
				Log.i(TAG, "----->arg0:" + arg0.toString());
				String result = null;
				try {
					result = CodecUtils.base64Decode(arg0.toString());
				} catch (Exception e) {
					mMessage.what = UIHelper.SIGNIN_UPLOAD_ERROR;
					send();
					return;
				}
				Log.i(TAG, "----->Result:" + result);
				SigninRecordResp bean = new GsonBuilder().create().fromJson(
						result, SigninRecordResp.class);
				if (bean != null && !bean.isEmpty()) {
					String id = bean.getValues().get(0);
					// 跟新数据库数据
					// String flag = mSignInRecordBean.getFlag();
					String type = mSignInRecordBean.getType();
					if (type.equals(DataConfig.REGISTER_TYPE_2)
							|| type.equals(DataConfig.REGISTER_TYPE_3)) {
						// 个别签到
						// 同时更新图片或者录音
						mSignInRecordBean.setEduComld(id);
						try {
							List<ImageOrAudioBean> imageOrAudioBeans = mKjdb
									.findAllByWhere(
											ImageOrAudioBean.class,
											"serviceId = 2 and parentId = '"
													+ String.valueOf(mSignInRecordBean
															.getId())
													+ "' and fileType = 1");
							if (imageOrAudioBeans != null
									&& !imageOrAudioBeans.isEmpty()) {
								for (ImageOrAudioBean image : imageOrAudioBeans) {
									if (image != null) {
										image.setSponsorId(id);
										mKjdb.update(image);
									}
								}
							}
						} catch (Exception e) {

						}
						// uploadSource();
					}
					Log.i(TAG, "--001--->mSignInRecordBean:" + mSignInRecordBean.toString());
					mSignInRecordBean.setState(2);
					mKjdb.update(mSignInRecordBean);
					mCurrentIndex++;
					uploadSignInfo();
				} else {
					mMessage.what = UIHelper.SIGNIN_UPLOAD_ERROR;
					send();
				}
			}

			@Override
			public void onLoading(long arg0, long arg1) {
				Log.i(TAG, "----->Result:arg0:" + arg0 + ",arg1:" + arg1);
			}

			@Override
			public void onFailure(Throwable arg0, int arg1, String arg2) {
				Log.i(TAG, "----->Result:arg1:" + arg1 + ",arg2:" + arg2);
				mMessage.what = UIHelper.SIGNIN_UPLOAD_FAIL;
				send();
			}
		});

	}

	// 上传资源
	private void uploadSource() {
		mParams = new KJFileParams();
		mParams.put(AppGlobal.HTTP_PARAM_IMEI, mImei);
		mParams.put("serviceId", "2");
		mParams.put("eduComId", mSignInRecordBean.getEduComld());
		try {
			File file = new File(mSignInRecordBean.getFilePath());
			FileInputStream stream = new FileInputStream(file);
			mParams.put("fileInput", stream, file.getName());
			mParams.put("fileInputFileName", file.getName());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			mMessage.what = UIHelper.SIGNIN_UPLOAD_ERROR;
			send();
			return;
		}
		String url = HttpConfig.POST_URL_FILEUPLOAD_UPLOADTOTEMP;
		Log.i(TAG, "----->API:" + url);
		KJHttp kjHttp = new KJHttp();
		kjHttp.post(url, mParams, new HttpCallBack() {

			@Override
			public void onSuccess(Object arg0) {
				Log.i(TAG, "----->arg0:" + arg0.toString());
				String result = null;
				try {
					result = CodecUtils.base64Decode(arg0.toString());
				} catch (Exception e) {
					mMessage.what = UIHelper.SIGNIN_UPLOAD_ERROR;
					send();
					return;
				}
				Log.i(TAG, "----->Result:" + result);
				BaseBean baseBean = new GsonBuilder().create().fromJson(result,
						BaseBean.class);
				if (baseBean != null && baseBean.isSuccess()) {
					mMessage.what = UIHelper.SIGNIN_UPLOAD_SUCCESS;
					mMessage.obj = mSignInRecordBean.getEduComld();
					send();
				} else {
					mMessage.what = UIHelper.SIGNIN_UPLOAD_ERROR;
					send();
				}
			}

			@Override
			public void onLoading(long arg0, long arg1) {
				Log.i(TAG, "----->Result:arg0:" + arg0 + ",arg1:" + arg1);
			}

			@Override
			public void onFailure(Throwable arg0, int arg1, String arg2) {
				Log.i(TAG, "----->Result:arg1:" + arg1 + ",arg2:" + arg2);
				mMessage.what = UIHelper.SIGNIN_UPLOAD_FAIL;
				send();
			}
		});

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub

	}

}
